{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "651fef7a",
   "metadata": {
    "origin_pos": 1
   },
   "source": [
    "# The Base Classification Model\n",
    ":label:`sec_classification`\n",
    "\n",
    "You may have noticed that the implementations from scratch and the concise implementation using framework functionality were quite similar in the case of regression. The same is true for classification. Since many models in this book deal with classification, it is worth adding functionalities to support this setting specifically. This section provides a base class for classification models to simplify future code.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e1dd1359",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T20:14:28.524732Z",
     "iopub.status.busy": "2023-08-18T20:14:28.524009Z",
     "iopub.status.idle": "2023-08-18T20:14:31.450273Z",
     "shell.execute_reply": "2023-08-18T20:14:31.448972Z"
    },
    "origin_pos": 3,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70bc0d4e",
   "metadata": {
    "origin_pos": 6
   },
   "source": [
    "## The `Classifier` Class\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "641cbe3d",
   "metadata": {
    "origin_pos": 7,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "We define the `Classifier` class below. In the `validation_step` we report both the loss value and the classification accuracy on a validation batch. We draw an update for every `num_val_batches` batches. This has the benefit of generating the averaged loss and accuracy on the whole validation data. These average numbers are not exactly correct if the final batch contains fewer examples, but we ignore this minor difference to keep the code simple.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1bb74037",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T20:14:31.455489Z",
     "iopub.status.busy": "2023-08-18T20:14:31.454488Z",
     "iopub.status.idle": "2023-08-18T20:14:31.461017Z",
     "shell.execute_reply": "2023-08-18T20:14:31.460154Z"
    },
    "origin_pos": 9,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class Classifier(d2l.Module):  #@save\n",
    "    \"\"\"The base class of classification models.\"\"\"\n",
    "    def validation_step(self, batch):\n",
    "        Y_hat = self(*batch[:-1])\n",
    "        self.plot('loss', self.loss(Y_hat, batch[-1]), train=False)\n",
    "        self.plot('acc', self.accuracy(Y_hat, batch[-1]), train=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5244291",
   "metadata": {
    "origin_pos": 11
   },
   "source": [
    "By default we use a stochastic gradient descent optimizer, operating on minibatches, just as we did in the context of linear regression.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3d1c1bb6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T20:14:31.464177Z",
     "iopub.status.busy": "2023-08-18T20:14:31.463903Z",
     "iopub.status.idle": "2023-08-18T20:14:31.468562Z",
     "shell.execute_reply": "2023-08-18T20:14:31.467672Z"
    },
    "origin_pos": 13,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "@d2l.add_to_class(d2l.Module)  #@save\n",
    "def configure_optimizers(self):\n",
    "    return torch.optim.SGD(self.parameters(), lr=self.lr)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28232a31",
   "metadata": {
    "origin_pos": 16
   },
   "source": [
    "## Accuracy\n",
    "\n",
    "Given the predicted probability distribution `y_hat`,\n",
    "we typically choose the class with the highest predicted probability\n",
    "whenever we must output a hard prediction.\n",
    "Indeed, many applications require that we make a choice.\n",
    "For instance, Gmail must categorize an email into \"Primary\", \"Social\", \"Updates\", \"Forums\", or \"Spam\".\n",
    "It might estimate probabilities internally,\n",
    "but at the end of the day it has to choose one among the classes.\n",
    "\n",
    "When predictions are consistent with the label class `y`, they are correct.\n",
    "The classification accuracy is the fraction of all predictions that are correct.\n",
    "Although it can be difficult to optimize accuracy directly (it is not differentiable),\n",
    "it is often the performance measure that we care about the most. It is often *the*\n",
    "relevant quantity in benchmarks. As such, we will nearly always report it when training classifiers.\n",
    "\n",
    "Accuracy is computed as follows.\n",
    "First, if `y_hat` is a matrix,\n",
    "we assume that the second dimension stores prediction scores for each class.\n",
    "We use `argmax` to obtain the predicted class by the index for the largest entry in each row.\n",
    "Then we [**compare the predicted class with the ground truth `y` elementwise.**]\n",
    "Since the equality operator `==` is sensitive to data types,\n",
    "we convert `y_hat`'s data type to match that of `y`.\n",
    "The result is a tensor containing entries of 0 (false) and 1 (true).\n",
    "Taking the sum yields the number of correct predictions.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b132abd8",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T20:14:31.471739Z",
     "iopub.status.busy": "2023-08-18T20:14:31.471463Z",
     "iopub.status.idle": "2023-08-18T20:14:31.477124Z",
     "shell.execute_reply": "2023-08-18T20:14:31.476264Z"
    },
    "origin_pos": 17,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "@d2l.add_to_class(Classifier)  #@save\n",
    "def accuracy(self, Y_hat, Y, averaged=True):\n",
    "    \"\"\"Compute the number of correct predictions.\"\"\"\n",
    "    Y_hat = Y_hat.reshape((-1, Y_hat.shape[-1]))\n",
    "    preds = Y_hat.argmax(axis=1).type(Y.dtype)\n",
    "    compare = (preds == Y.reshape(-1)).type(torch.float32)\n",
    "    return compare.mean() if averaged else compare"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47696b41",
   "metadata": {
    "origin_pos": 20
   },
   "source": [
    "## Summary\n",
    "\n",
    "Classification is a sufficiently common problem that it warrants its own convenience functions. Of central importance in classification is the *accuracy* of the classifier. Note that while we often care primarily about accuracy, we train classifiers to optimize a variety of other objectives for statistical and computational reasons. However, regardless of which loss function was minimized during training, it is useful to have a convenience method for assessing the accuracy of our classifier empirically. \n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Denote by $L_\\textrm{v}$ the validation loss, and let $L_\\textrm{v}^\\textrm{q}$ be its quick and dirty estimate computed by the loss function averaging in this section. Lastly, denote by $l_\\textrm{v}^\\textrm{b}$ the loss on the last minibatch. Express $L_\\textrm{v}$ in terms of $L_\\textrm{v}^\\textrm{q}$, $l_\\textrm{v}^\\textrm{b}$, and the sample and minibatch sizes.\n",
    "1. Show that the quick and dirty estimate $L_\\textrm{v}^\\textrm{q}$ is unbiased. That is, show that $E[L_\\textrm{v}] = E[L_\\textrm{v}^\\textrm{q}]$. Why would you still want to use $L_\\textrm{v}$ instead?\n",
    "1. Given a multiclass classification loss, denoting by $l(y,y')$ the penalty of estimating $y'$ when we see $y$ and given a probabilty $p(y \\mid x)$, formulate the rule for an optimal selection of $y'$. Hint: express the expected loss, using $l$ and $p(y \\mid x)$.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "398f847c",
   "metadata": {
    "origin_pos": 22,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/6809)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}